import { defineStore } from "pinia";
import { Message } from "@arco-design/web-vue";
import * as productApi from "@/api/product";

export const useProductStore = defineStore("product", () => {
  async function getProductList(param?: any) {
    const response = await productApi.getProductList(param);
    if (response.code === 20000) {
      return response.data.products;
    }
    return [];
  }

  async function saveProduct(param?: any) {
    const apiCall = param.id
      ? productApi.updateProduct
      : productApi.createProduct;
    const response = await apiCall({ ...param });
    if (response.code === 20000) {
      Message.success(param.id ? "更新成功" : "新增成功");
    }
  }

  async function deleteProduct(param?: any) {
    const response = await productApi.deleteProduct(param);
    if (response.code === 20000) {
      Message.success("移除成功");
    }
  }

  async function getCategoryList(param?: any) {
    const response = await productApi.getProductCategoryList(param);
    if (response.code === 20000) {
      return response.data.productCategories;
    }
    return [];
  }

  async function saveCategory(param?: any) {
    const apiCall = param.id
      ? productApi.updateProductCategory
      : productApi.createProductCategory;
    const response = await apiCall({ ...param });
    if (response.code === 20000) {
      Message.success(param.id ? "更新成功" : "新增成功");
    }
  }

  async function deleteCategory(param?: any) {
    const response = await productApi.deleteProductCategory(param);
    if (response.code === 20000) {
      Message.success("移除成功");
    }
  }

  async function updateCategories(param?: any) {
    const response = await productApi.updateCategories(param);
    if (response.code === 20000) {
      Message.success("更新成功");
    }
  }

  async function getCategory(param?: any) {
    const response = await productApi.getCategory(param);
    if (response.code === 20000) {
      return response.data.productCategory;
    }
    return {};
  }

  return {
    getProductList,
    saveProduct,
    deleteProduct,
    getCategoryList,
    saveCategory,
    deleteCategory,
    updateCategories,
    getCategory,
  };
});
